import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/pages/payment/widgets/app_bar_actions.dart';
import 'package:yyshort/pages/payment/widgets/restore_button.dart';
import 'package:yyshort/pages/payment/widgets/ticket_component.dart';
import 'package:yyshort/pages/payment/widgets/vip_card.dart';

import 'controller.dart';
import 'widgets/connection_check_tile.dart';
import 'widgets/product_list.dart';
import 'widgets/consumable_box.dart';

/// 内购页面主视图
/// 职责：构建UI界面，绑定控制器提供的数据和交互逻辑
// ignore: must_be_immutable
class PaymentView extends GetView<PaymentController> {
  EpisodeModel? episodeModel;
  bool? isShowInVideo;

  PaymentView({super.key, this.episodeModel, this.isShowInVideo = false});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () =>
              controller.state.isNeedLoading.value ? null : Get.back(),
        ),
        actions: Platform.isIOS ? [AppBarActions()] : [],
      ),
      body: SafeArea(child: buildView()),
    );
  }

  Widget buildView() {
    return Obx(() {
      // 显示加载状态
      if (controller.state.conTypeList.isEmpty &&
          controller.state.subTypeList.isEmpty) {
        return Center(child: CircularProgressIndicator());
      }

      return Stack(
        children: [
          Column(
            children: [
              // 订阅类型VIP卡片区域
              if (controller.state.products.isNotEmpty &&
                  controller.state.subTypeList.isNotEmpty)
                Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.all(8.0),
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          'VIP 订阅'.tr,
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 120,
                      child: IgnorePointer(
                        // true表示禁止手势，false表示允许
                        ignoring: controller.state.isNeedLoading.value,
                        child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Row(
                              children: controller.state.subTypeList.map((
                                goods,
                              ) {
                                return VipCard(
                                  title: goods.name ?? '',
                                  description: goods.desc ?? '',
                                  price:
                                      '\$${goods.goodUsPrice?.toStringAsFixed(2) ?? ''}',
                                  goods: goods,
                                  onPurchase: () {
                                    if (episodeModel != null) {
                                      controller.state.episodeModel =
                                          episodeModel;
                                    }
                                    controller.clickGoods(goods);
                                  },
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              // 充值区域
              _buildRefillSection(),
            ],
          ),

          // controller.state.isNeedLoading.value
          //     ? Center(child: CircularProgressIndicator())
          //     : SizedBox(),
        ],
      );
    });
  }

  Widget _buildRefillSection() {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '充值'.tr,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 10),
            Expanded(
              child: Obx(() {
                return IgnorePointer(
                  ignoring: controller.state.isNeedLoading.value,
                  child: GridView.builder(
                    physics: isShowInVideo!
                        ? NeverScrollableScrollPhysics()
                        : AlwaysScrollableScrollPhysics(),
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          crossAxisSpacing: 8,
                          mainAxisSpacing: 8,
                          childAspectRatio: 1,
                        ),
                    itemCount: controller.state.products.isNotEmpty
                        ? controller.state.conTypeList.length
                        : 0,
                    itemBuilder: (context, index) {
                      final goods = controller.state.conTypeList[index];
                      // return Container(
                      //   width: 170.w,
                      //   height: 129.h,
                      //   color: Colors.red,
                      // );

                      return TicketComponent(
                        goods: goods,
                        onTap: () => controller.clickGoods(goods),
                      );
                    },
                  ),
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}

// 测试页面
//   @override
//   Widget build(BuildContext context) {
//     // // 初始化商店信息（查询商品列表等）
//     // controller.initStoreInfo();

//     // 使用Obx监听状态变化，当状态改变时自动重建UI
//     return Obx(() {
//       // 构建页面内容堆叠
//       final List<Widget> stack = <Widget>[];

//       // 根据错误状态展示不同内容
//       if (controller.state.queryProductError.value == null ||
//           controller.state.queryProductError.value.isEmpty) {
//         // 无错误时展示商品列表等内容
//         stack.add(
//           ListView(
//             children: <Widget>[
//               // 连接状态检查组件
//               // ConnectionCheckTile(controller: controller),
//               // 商品列表组件
//               ProductList(controller: controller),
//               // 消耗品展示组件
//               // ConsumableBox(controller: controller),
//               // 恢复购买按钮
//               RestoreButton(controller: controller),
//             ],
//           ),
//         );
//       } else {
//         // 有错误时展示错误信息C
//         stack.add(
//           Center(child: Text(controller.state.queryProductError.value)),
//         );
//       }

//       // 购买处理中时显示加载指示器
//       if (controller.state.purchasePending.value) {
//         stack.add(
//           const Stack(
//             children: <Widget>[
//               // 半透明遮罩
//               Opacity(
//                 opacity: 0.3,
//                 child: ModalBarrier(dismissible: false, color: Colors.grey),
//               ),
//               // 加载指示器
//               Center(child: CircularProgressIndicator()),
//             ],
//           ),
//         );
//       }

//       // 页面整体结构
//       return Scaffold(
//         appBar: AppBar(title: const Text('In-App Purchase Example')),
//         body: Stack(children: stack),
//       );
//     });
//   }
// }
